CS 211 Lesson 4
Operations and Built-in Functions
Quote:
When a man has strong qualities of leadership, but is of low moral character, there is always the danger that his subordinates will be influenced by his bad characteristics, to the detriment of the leader and of the group. But if the leader is a man of strong qualities of leadership and high moral character, he will endure and he will achieve better results. Edgar F. Puryear
Lesson Objectives:
Understand the difference between MATLAB's scalar, array, and matrix operations
Be able to use scalar, array, and matrix operations
Understand MATLAB's operator precedence
Be able to find and use MATLAB's built-in functions
Lesson:
I. MATLAB Concepts
A. MATLAB Operations
An operation is a common mathematical function assigned a special character operator (some operators are defined as more than one character).
The most common MATLAB operations are:
Addition (+)
Subtraction (-)
Multiplication (*, .*)
Division (/, ./)
Exponentiation (^, .^)
Negation (unary -)
For the most part, these operators behave as you would expect, except when multiplying matrices.
As described below, the dot prefix distinguishes between array and matrix operations.
B. Scalar Operations
A scalar value is a single-element value (a variable that is a 1-row and 1-column array).
MATLAB operations behave differently for scalar and non-scalar values.
A scalar operation has a scalar value as one or both of its operands.
With a scalar operation, the operation is applied to the scalar value and each element of the other value.
For example:
Scale = 2
Dimensions = [10 20 30]
Four = Scale * 2
Doubled = Dimensions * Scale
Tens = 10*ones(5)
% scalar
% vector
% scalar * scalar
% vector * scalar
% scalar * matrixC. Array operations
An array operation is applied element-by-element between two matrices.
Operands of an array operation must have the same shape (same number of rows and columns).
Array multiply (.*), divide (./), and exponentiation (.^) operators have a period prefix.
Experiment with the following examples:
V1 = 1:3
V2 = 4:6
V3 = V1 + V2
% size = 1x3
% size = 1x3
% array addition
M1 = [1:4; 5:8]
M2 = ones(2, 4)
M3 = M1 - M2
% size = 2 x 4
% size = 2 x 4
% array subtraction
V1 = 1:3
V2 = 4:6
V3 = V1 .* V2
% size = 1x3
% size = 1x3
% array multiplication
M1 = [1:4; 5:8]
M2 = [1:4; 10:13]
M3 = M1 ./ M2
% size = 2 x 4
% size = 2 x 4
% array division
V1 = 1:3
V2 = 2 .^ V1
V3 = V1 .^ 2
% size = 1x3
% array exponentiation
% array exponentiation
D. Matrix Operations
A matrix operation is a matrix multiplication, division, or exponentiation between two matrices.
Matrix multiply (*), divide (/), and exponentiation (^) operators do not have a period prefix.
Using the notation C = A * B, matrix multiplication has the following properties:
the number of columns of A must equal the number of rows of B.
c(i, j) = sum (k=1 to n) a(i, k)*b(k, j) where n is the number of columns of A (and rows of B).
C will have the same number of rows as A and the same number of columns as B.
The identity matrix is defined as a square matrix with zeros for every element except the left-to-right diagonal elements which are 1.0. The MATLAB function eye(n) will create an identity matrix with n rows and n columns.
A matrix, multiplied by its inverse, always results in the identity matrix. The MATLAB function inv(A) will calculate the inverse of a square matrix A. (Some matrices do not have an inverse.)
Using the notation C = A / B, matrix division is calculated as C = A * inv(B) and has the following properties:
the matrix B must be square
the matrix A must have the same number of columns as the size of B
assuming that an inverse for B exists, the calculated matrix C, times B, will always equal A.
Experiment with the following examples:
V1 = 1:3
V2 = [4:6]'
S = V1 * V2
V1 = 1:3
V2 = [4:6]'
M1 = V2 * V1
% size = 1x3
% size = 3x1
% matrix multiplication - results in a 1x1 array
% size = 1x3
% size = 3x1
% matrix multiplication - results in a 3x3 array
M1 = rand(3)
M2 = rand(3)
M3 = M1 / M2
M4 = M3 * M2
% size = 3 x 3
% size = 3 x 3
% matrix division
% Test: Is M4 is now the same as M1?
V1 = [1:3; 4:6; 7:9]
V2 = 2 ^ V1
V2 = V1 ^ 2
V2 = V1 ^ V1
% size = 3x3 - must be square for exponentiation
% matrix exponentiation - a scalar raised to a matrix power
% matrix exponentiation - a matrix raised to a scalar power
% matrix exponentiation - a matrix raised to a matrix power
% invalid and always an error
M1 = [1:4; 5:8]
M2 = ones(2, 4)
Error = M1 * M2
% size = 2 x 4
% size = 2 x 4
% invalid matrix multiplication because M1 does not
% have the same number of columns as the rows of M2
E. Operator Precedence
Operator precedence determines the order in which operators get evaluated by the MATLAB interpreter.
MATLAB uses the standard mathematical operator precedence (order of operations).
From highest to lowest, MATLAB's operator precedence rules are:
the contents of parentheses are evaluated first starting with the innermost parentheses and working out
exponentials are evaluated working from left to right
multiplications and divisions are evaluated working from left to right
additions and subtractions are evaluated working from left to right
For complex expressions, use parentheses liberally to make the order of evaluation clear.
MATLAB's editor helps in balancing parentheses -- click on a left parenthesis and the corresponding right parenthesis will be underlined.
F. Built-in Functions
A function is a mapping from zero or more input values (in the domain) to a single output value (in the range).
A MATLAB function
has a name (usually in all lower case)
takes zero or more input arguments enclosed in parentheses
returns a single value by default (if an error does not occur)
MATLAB functions may return multiple named values (unlike mathematical functions)
MATLAB provides many "built-in" functions you may use at the command line or in your programs.
Some common MATLAB, built-in functions are:
Function Description abs(x) absolute value sqrt(x) square root sin(x), cos(x), tan(x) trigonometric functions asin(x), acos(x), atan(x), atan2(x,y) inverse trigonometric functions (e.g., arc sin) exp(x), log(x) natural number exponentiation (ex, loge x) mod(x, y) remainder after division (modulus) mean(vector) calculate the average value of a series of values sum(vector) calculate the sum of all values in the vector [value, index] = max(vector) find the value and location of the largest element of an array [value, index] = min(vector) find the value and location of the smallest element of an array ceil(x) nearest integer towards positive infinity floor(x) nearest integer towards minus infinity round(x) nearest integer fix(x) nearest integer towards zero num2str(number) convert a number into a string str2num(string) convert a string into a number The MATLAB help function (and "help" windows) provides an excellent function reference with good examples to follow.
Most MATLAB functions operate on scalars, vectors, and matrices.
When applied to 2-D matrices, almost all functions are applied column-by-column and return a row vector. For example:
max(3)
max([2 5 4])
max([2 5 4; 3 1 6])
max(max([2 5 4; 3 1 6]))
Some functions have optional return values. For example:
biggest = max([2 5 4])
[biggest index] = max([2 5 4 3 7 1 6])
Functions with no input arguments may be called without parentheses, but this is "bad style" and should be avoided.
date
clock
Functions with no input arguments should be called with empty parentheses (especially in programs) to avoid confusion with variables.
date()
clock()
II. Good Programming Practices
When performing mathematical operations,
always take special care to distinguish between array (element-by-element) operations and matrix operations.
use parentheses to group operations in the order you desire them to happen.
leave appropriate spaces in an equation to make it
easier to read.
When creating your own functions, always start your function name with an upper-case letter - this will guarantee that your functions never "hide" built-in functions.
III. Algorithms
A. Solve a system of n equations containing n unknowns
For example, consider the 3 equations below involving the 3 unknowns x, y, and z
3x + 4y - 5z = 23
7x - 2y + 3z = 5
4x + 5y - 7z = 12
These 3 equations can be written in matrix form as follows:
Let
M = [3 4 -5; 7 -2 3; 4 5 -7];
% V = [x y z]; We don't actually create this
S = [23; 5; 12];
Therefore, M * V = S
To solve for V, multiply both sides by M-1(inverse of M). This cancels out the M matrix on the left hand side of the equation. The order of matrix multiplication matters (e.g., A * B is typically not equal to B * A). Therefore, the order of the operations must be as shown below.
inv(M) * M * V = inv(M) * S
V = inv(M) * S
Lab Work: Lab 4
References: Chapman Textbook: sections 2.8-2.10